package com.tywj.buscustomerapp.view.activity;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.utils.CheckFormatUtil;
import com.tywj.buscustomerapp.utils.PhoneUtils;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {
    @BindView(R.id.head_left)
    ImageView back;
    @BindView(R.id.head_title)
    TextView headtitle;
    @BindView(R.id.login_phone)
    EditText phoneEdit;
    @BindView(R.id.login_pwd)
    EditText pwdEdit;
    @BindView(R.id.login_clear)
    ImageView clear;
    @BindView(R.id.login_submit)
    TextView  submit;
    @BindView(R.id.to_register)
    TextView doRegister;
    @BindView(R.id.to_forget)
    TextView doForget;
    @BindView(R.id.use_info)
    TextView use_info;
    @BindView(R.id.head_right)
    TextView right;
    @Override
    protected int getContentId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        headtitle.setText(R.string.login);
        right.setText("注册");
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = phoneEdit.getText().toString();
                final String pwd = pwdEdit.getText().toString();
                if (phone.equals("")){
                    ToastJoe.getmToastJoe().ToastShow(LoginActivity.this,null,"请输入手机号");
                }else if (!CheckFormatUtil.checkPhone(phone)){
                    ToastJoe.getmToastJoe().ToastShow(LoginActivity.this,null,"请输入正确的手机号");
                }else if (pwd.equals("")){
                    ToastJoe.getmToastJoe().ToastShow(LoginActivity.this,null,"请输入密码");
                }else{
                    Observable.create(new ObservableOnSubscribe<String>() {
                        @Override
                        public void subscribe(ObservableEmitter<String> e){
                            try {
                                String mes = WebServicrUtils.getInstance().doLogin(phone,pwd);
                                Log.i("taylor",mes);
                                String[] message = mes.split(",");
                                if (message[0].equals("ok")){
                                    e.onNext(mes);
                                }else
                                    e.onError(null);
                            } catch (IOException e1) {
                                e.onError(e1);
                                e1.printStackTrace();
                            } catch (XmlPullParserException e1) {
                                e.onError(e1);
                                e1.printStackTrace();
                            }
                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<String>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(String s) {
                                    String[] message = s.split(",");
                                    String imei = getUserId();
                                    if (!message[2].equals("yes") && !imei.equals(message[1])){
                                        if (phone.equals("18193189810")){
                                            SPUtils.rememberUser(getApplicationContext(),phone,message[1]);
                                            setResult(1003, new Intent());
                                            finish();
                                        }else {
                                            if (message[1] == null || message[1].equals("")) {
                                                SPUtils.rememberUser(getApplicationContext(), phone, imei);
                                                setResult(1003, new Intent());
                                                finish();
                                            }
                                            ToastJoe.getmToastJoe().ToastLongShow(LoginActivity.this, null, "与上次登录设备不一致，请认证身份");
                                            Intent intent = new Intent(LoginActivity.this, RegisterUserCodeActivity.class);
                                            intent.putExtra("phone", phone);
                                            startActivity(intent);
                                        }
                                    }else {
                                        SPUtils.rememberUser(getApplicationContext(),phone,message[1]);
                                        setResult(1003, new Intent());
                                        finish();
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    ToastJoe.getmToastJoe().ToastLongShow(LoginActivity.this,null,"账号或密码错误请重新输入");
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }
            }
        });
        use_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,InfoActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });
        phoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = phoneEdit.getText().toString();
                if (!phone.equals("")){
                    clear.setVisibility(View.VISIBLE);
                }else{
                    clear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });

        doRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
            }
        });

        doForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,ForgotPwdActivity.class));
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = phoneEdit.getText().toString();
                if (!phone.equals("")){
                    phoneEdit.setText("");
                }
            }
        });
    }

    private String getUserId(){
        String onlyString = "";
        try{
            if (Build.VERSION.SDK_INT >= 26) {
                onlyString = PhoneUtils.getid(this);
            }else{
                onlyString = PhoneUtils.getIMid(this);
            }
            if (onlyString!=null && !onlyString.equals("")){
                return  onlyString;
            }
        }catch (Exception e){

        }
        if (onlyString==null || onlyString.equals("")){
            onlyString = PhoneUtils.getAndroidID(this);
        }
        if (onlyString==null || onlyString.equals("")){
            onlyString = PhoneUtils.getSerID(this);
        }
        return onlyString;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("登陆");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("登陆");
        MobclickAgent.onPause(this);
    }
}
